package com.itheima.baimi;

import javax.swing.*;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class Demo {

    public static void main(String[] args) {
        //计数闭锁  8个  齐了 开枪
        CountDownLatch countDownLatch = new CountDownLatch(8);
        // 同步屏障  9个   裁判 也开始
        CyclicBarrier cyclicBarrier = new CyclicBarrier(9);
        Judgment judgment = new Judgment(countDownLatch, cyclicBarrier);
        new Thread(judgment).start();
        for (int i = 0; i < 8; i++) {
            Player player = new Player(countDownLatch, cyclicBarrier);
            Thread t = new Thread(player);
            t.setName("运动员00"+i);
            t.start();
        }



    }
}

//裁判  数人   打枪
//打枪  就位卡着
class  Judgment implements Runnable{
    private CountDownLatch count;
    private CyclicBarrier cyclicBarrier;

    public Judgment(CountDownLatch count, CyclicBarrier cyclicBarrier) {
        this.count = count;
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            //奇数闭锁面前等着
            //裁判员  等  所有人就位
            count.await();
            // 打枪
            System.out.println("各就位预备 嘭");
            cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }



    }
}


//运动员  就位  跑
//跑之前  被枪声卡着
class  Player implements Runnable{
    private CountDownLatch count;
    private CyclicBarrier cyclicBarrier;
    public Player(CountDownLatch count, CyclicBarrier cyclicBarrier) {
        this.count = count;
        this.cyclicBarrier = cyclicBarrier;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        //  运动员 就位   cyclicBarrier .await
        try {
            Random r = new Random();
            int moji = r.nextInt(5000);
            Thread.sleep(moji);
            System.out.println(name+"墨迹了"+moji+"一会儿");
            System.out.println(name+"已经就绪");
            count.countDown();
            cyclicBarrier.await();
            System.out.println(name+"出发了");

            int time = r.nextInt(400) + 9580;
            Thread.sleep(time);
            System.out.println(name+"跑了"+time+"到达终点");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        //同时  CountDownLatch -1

    }
}